//
//  UNUserNotificationCenter+CalendarTrigger.m
//  UnionDrugBox
//
//  Created by duanan on 2020/1/20.
//  Copyright © 2020 duanan. All rights reserved.
//

#import "UNUserNotificationCenter+CalendarTrigger.h"

#import <UIKit/UIKit.h>


@implementation UNUserNotificationCenter (CalendarTrigger)


 
   
#pragma mark --  添加一个本地通知
/// ios10 添加本地推送，触发时间必须大于现在的系统时间，否则崩溃
/// @param title 标题
/// @param subTitle 副标题
/// @param body 内容
/// @param timeInterval 今天的时间单位s  00:00为0
/// @param identifier 本地推送消息的id，不可重复
/// @param userInfo 用户可以自定义字段
/// @param isDefault YES默认计划  NO今日执行计划
+ (void)addLocalNotificationWithTitle:(NSString *)title subTitle:(NSString *)subTitle body:(NSString *)body timeInterval:(long)timeInterval identifier:(NSString *)identifier userInfo:(NSDictionary *)userInfo isDefault:(BOOL)isDefault{
    
        int repeats = 7 ;
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd 00:00:00"];
        
       
        NSString *string = [formatter stringFromDate:date];
        NSLog(@"%@", string);
        //今天00:00点的时间戳
        NSTimeInterval TimeInterval1 = [[formatter dateFromString:string] timeIntervalSince1970];
        //明天00:00点的时间戳
        NSTimeInterval TimeInterval2 = TimeInterval1 + 60*60*24 ;
        NSTimeInterval timeEnd = timeInterval ;
        if (isDefault) {
            timeEnd = TimeInterval2 + timeInterval ;
            repeats = 4 ;
         }else{
            timeEnd = TimeInterval1 + timeInterval ;
            repeats = 7 ;
         }
        timeEnd = [[NSDate dateWithTimeIntervalSince1970:timeEnd] timeIntervalSinceNow];
    
     if (title.length == 0 || body.length == 0 || identifier.length == 0) {
         return;
     }
    
         UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
         UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    
       //  center.delegate = delegate ;
         // 标题
         if (title.length) {
             content.title = title;
         }
         if (subTitle.length) {
             content.subtitle = subTitle;
         }
         // 内容
         if (body.length) {
             content.body = body;
         }
         if (userInfo != nil) {
             content.userInfo = userInfo;
         }
         // 声音
         // 默认声音
        if (@available(iOS 12.0, *)) {
           content.sound = [UNNotificationSound soundNamed:@"222.caf"];
//           content.sound = [UNNotificationSound criticalSoundNamed:@"222.caf"];
         } else {
           content.sound = [UNNotificationSound soundNamed:@"222.caf"];
        }
         // 添加自定义声音
         //content.sound = [UNNotificationSound soundNamed:@"Alert_ActivityGoalAttained_Salient_Haptic.caf"];
         // 角标 （我这里测试的角标无效，暂时没找到原因）
         content.badge = @1;
         // 多少秒后发送,可以将固定的日期转化为时间
        
         UNNotificationTrigger *trigger = nil;
         // repeats，是否重复，如果重复的话时间必须大于60s，要不会报错
         if (repeats > 0 && repeats < 7) {
 
             NSDate *date =[NSDate dateWithTimeIntervalSince1970:timeEnd] ;
             // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
             unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitWeekday | NSCalendarUnitMinute | NSCalendarUnitSecond;
             NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
             // 获取不同时间字段的信息
             NSDateComponents* comp = [gregorian components:unitFlags fromDate:date];
             NSDateComponents *components = [[NSDateComponents alloc] init];
             components.second = comp.second;
             if (repeats == 6) {
                 //每分钟循环
             } else if (repeats == 5) {
                 //每小时循环
                 components.minute = comp.minute;
             } else if (repeats == 4) {
                 //每天循环
                 components.minute = comp.minute;
                 components.hour = comp.hour;
             } else if (repeats == 3) {
                 //每周循环
                 components.minute = comp.minute;
                 components.hour = comp.hour;
                 components.weekday = comp.weekday;
             } else if (repeats == 2) {
                 //每月循环
                 components.minute = comp.minute;
                 components.hour = comp.hour;
                 components.day = comp.day;
                 components.month = comp.month;
             } else if (repeats == 1) {
                 //每年循环
                 components.minute = comp.minute;
                 components.hour = comp.hour;
                 components.day = comp.day;
                 components.month = comp.month;
                 components.year = comp.year;
             }
             trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
         } else {
             //不循环
             trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:timeEnd repeats:NO];
         }
         // 添加通知的标识符，可以用于移除，更新等操作 identifier
         UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
         [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
             NSLog(@"添加本地推送成功");
         }];
  }


#pragma mark -- 移除所有通知
+ (void)removeAllNotification
{
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center removeAllPendingNotificationRequests];
}


#pragma mark -- 检测通知 开关状态
+ (void)checkNotificationSwitchState:(void (^)(bool isOopen))back{
    UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter];
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        if (settings.notificationCenterSetting == UNNotificationSettingEnabled) {
            NSLog(@"通知权限开启");
            back(YES) ;
        }else{
            NSLog(@"通知权限关闭");
            back(NO);
        }
    }];
}

#pragma mark -- 获取当前还存在的本地通知
+ (void)localNotification:(NotificationBlock)back{
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
        
        NSMutableArray* list = [NSMutableArray array];
        for (UNNotificationRequest *req in requests){
            NSLog(@"当前存在的本地通知identifier: %@\n", req.identifier);
            [list addObject:req.identifier];
        }
        back(list);
    }];
}




@end
